package com.jingwu.example.service

import com.jingwu.example.pojo.entity.UserDO
import com.jingwu.example.repository.UserRepository
import org.springframework.boot.test.mock.mockito.MockBean
import org.springframework.context.annotation.Import
import org.springframework.test.context.ContextConfiguration
import spock.lang.Specification

import javax.annotation.Resource

import static org.mockito.Mockito.when

/**
 * 通过 Mockito 的 @MockBean 来注入 mock bean
 *
 * @author 菁芜
 * @since 2021/11/20 - 15:00
 */
@Import(UserService.class)
@ContextConfiguration
class UserService2Test extends Specification {

    @Resource
    UserService service;

    @MockBean
    UserRepository repositoryMB;

    def "getUser by mockito"() {
        given:
        def user1 = new UserDO(id: 1, username: "爆爆", age: 8)
        def user2 = new UserDO(id: 2, username: "金克丝", age: 16)

        and:
        when(repositoryMB.selectById(1)).thenReturn(user1)
        when(repositoryMB.selectById(2)).thenReturn(user2)

        when:
        def user = service.getUser(2)

        then:
        with(user) {
            user.username == "金克丝"
            user.age == 16
        }
    }
}
